package eraserhead.controller;

import eraserhead.boundary.DecisionGUI;
import eraserhead.boundary.StartForm;
import eraserhead.boundary.WarningWindow;
import eraserhead.entity.Decision;
import eraserhead.entity.Line;

/**
 * Controller for starting the rounds in a {@link Decision}
 * @author Greg
 */
public class StartRoundsController {
	Decision model;
	DecisionGUI view;
	StartForm startForm;
	
	/**
	 * Create a new {@link StartRoundsController}
	 * @param model {@link Decision} model to control
	 * @param view {@link DecisionGUI} associated with the model
	 */
	public StartRoundsController(Decision model, DecisionGUI view) {
		this.model = model;
		this.view = view;
	}
	
	public void process() {
		if (model.isOpen()) {
			int assumedNumUsers = 0;
			for (Line l : model.getLines()) {
				if (l.getChoice().length() > 0) {
					assumedNumUsers++;
				}
			}
			model.setUsers(assumedNumUsers);
		}
		if (model.isReady()) {
			/*if (model.getFormSent() == false)
			{
				String[] choices = new String[model.getNumUsers()];
				for(int i = 0; i<model.getNumUsers(); i++)
				{
					choices[i] = model.getLines().get(i).getChoice();
				}
				ServerAccess sa = ServerAccessManager.getAccess();
				CreateClosedRequest.send(sa, view.getQuestionTextField().getText(), model.getNumUsers(), model.getNumRounds(), 
						choices, model.getSignedInAs().getName(), model.getSignedInAs().getPassword());
				model.setFormSent(true);
			}*/
			if (model.usersAllHere()) {
				processAnyway();
			} else {
				startForm = new StartForm(model, view);
				startForm.setVisible(true);
			}
		} else {
			WarningWindow.giveWarning(view, "Please give at least 3 choices.");
		}
	}
	
	/**
	 * Like process, but doesn't care if users are here or not
	 */
	public void processAnyway() {
		if (!model.usersAllHere()) {
			model.resetNumUsers();
			model.resetLines();
			/*if (!model.resetNumUsers(model.getUsers())) {
				WarningWindow.giveWarning(view, model.getErrorMsg());
				return;
			}
			if (!model.resetLines()) {
				WarningWindow.giveWarning(view, model.getErrorMsg());
				return;
			}*/
			//view.getLinesCanvas().setCanAddEdge(true);
			//view.getChoicePanel().setCanGiveChoice(false);
			//view.lockStartButton();
		}
		view.getLinesCanvas().setCanAddEdge(true);
		view.getChoicePanel().setCanGiveChoice(false);
		view.lockStartButton();
		new UserController(model, view.getChoicePanel()).process();
	}
	
	public StartForm getStartForm()
	{
		return startForm;
	}
}
